package com.demo.kafka.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.util.Properties;

public class TransactionProducer {
    public static void main(String[] args) {
        //1、编写配置
        Properties properties = new Properties();
        //kafka 集群，bootstrap.servers
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:19092,localhost:19093,localhost:19094");
        //ack应答级别
        properties.put(ProducerConfig.ACKS_CONFIG, "all");
        //key值序列化
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");
        //value值序列化
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringSerializer");

        // 1、设置事务 id（必须），事务 id 任意起名
        properties.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "transaction_id_0");

        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<String, String>(properties);

        // 2、初始化事务
        kafkaProducer.initTransactions();
        // 3、开启事务
        kafkaProducer.beginTransaction();

        try {
            for (int i = 0; i < 10; i++) {
                //4、发送消息
                kafkaProducer.send(new ProducerRecord<String, String>("fzk", "fzk -- " + i));
                // 5、提交事务
                kafkaProducer.commitTransaction();
            }
        } catch (Exception e) {
            // 6、终止事务
            kafkaProducer.abortTransaction();
        } finally {
            if(kafkaProducer != null){
                kafkaProducer.close();
            }
        }
    }
}
